package com.baselibrary.utils;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.AppOpsManager;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.graphics.Point;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Binder;
import android.os.Build;
import android.os.IBinder;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.LongSparseArray;
import android.util.SparseArray;
import android.util.SparseBooleanArray;
import android.util.SparseIntArray;
import android.util.SparseLongArray;
import android.util.TypedValue;
import android.view.Display;
import android.view.KeyCharacterMap;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.WindowManager;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;

import androidx.collection.SimpleArrayMap;
import androidx.core.app.AppOpsManagerCompat;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSON;
import com.baselibrary.R;
import com.meiqia.meiqiasdk.util.MQIntentBuilder;

import org.jetbrains.annotations.NotNull;

import java.io.UnsupportedEncodingException;
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.URLDecoder;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

public class CommonUtil {

    //目标项是否在最后一个可见项之后
    private static boolean mShouldScroll;
    //记录目标项位置
    private static int mToPosition;

    /**
     * 滑动到指定位置
     */
    public static void smoothMoveToPosition(RecyclerView mRecyclerView, final int position) {
        // 第一个可见位置
        int firstItem = mRecyclerView.getChildLayoutPosition(mRecyclerView.getChildAt(0));
        // 最后一个可见位置
        int lastItem = mRecyclerView.getChildLayoutPosition(mRecyclerView.getChildAt(mRecyclerView.getChildCount() - 1));
        if (position < firstItem) {
            // 第一种可能:跳转位置在第一个可见位置之前
            mRecyclerView.smoothScrollToPosition(position);
        } else if (position <= lastItem) {
            // 第二种可能:跳转位置在第一个可见位置之后
            int movePosition = position - firstItem;
            if (movePosition >= 0 && movePosition < mRecyclerView.getChildCount()) {
                int top = mRecyclerView.getChildAt(movePosition).getTop();
                mRecyclerView.smoothScrollBy(0, top);
            }
        } else {
            // 第三种可能:跳转位置在最后可见项之后
            mRecyclerView.smoothScrollToPosition(position);
            mToPosition = position;
            mShouldScroll = true;
        }

    }


    /**
     * 以指定的分隔符来进行字符串元素连接
     * <p>
     * 例如有字符串数组array和连接符为逗号(,)
     * <code>
     * String[] array = new String[] { "hello", "world", "qiniu", "cloud","storage" };
     * </code>
     * 那么得到的结果是:
     * <code>
     * hello,world,qiniu,cloud,storage
     * </code>
     * </p>
     *
     * @param array 需要连接的字符串数组
     * @param sep   元素连接之间的分隔符
     * @return 连接好的新字符串
     */
    public static String join(String[] array, String sep) {
        if (array == null) {
            return null;
        }

        int arraySize = array.length;
        int sepSize = 0;
        if (sep != null && !sep.equals("")) {
            sepSize = sep.length();
        }

        int bufSize = (arraySize == 0 ? 0 : ((array[0] == null ? 16 : array[0].length()) + sepSize) * arraySize);
        StringBuilder buf = new StringBuilder(bufSize);

        for (int i = 0; i < arraySize; i++) {
            if (i > 0) {
                buf.append(sep);
            }
            if (array[i] != null) {
                buf.append(array[i]);
            }
        }
        return buf.toString();
    }

    public static Activity getCurrentActivity() {
        try {
            Class activityThreadClass = Class.forName("android.app.ActivityThread");
            Object activityThread = activityThreadClass.getMethod("currentActivityThread").invoke(
                    null);
            Field activitiesField = activityThreadClass.getDeclaredField("mActivities");
            activitiesField.setAccessible(true);
            Map activities = (Map) activitiesField.get(activityThread);
            for (Object activityRecord : activities.values()) {
                Class activityRecordClass = activityRecord.getClass();
                Field pausedField = activityRecordClass.getDeclaredField("paused");
                pausedField.setAccessible(true);
                if (!pausedField.getBoolean(activityRecord)) {
                    Field activityField = activityRecordClass.getDeclaredField("activity");
                    activityField.setAccessible(true);
                    Activity activity = (Activity) activityField.get(activityRecord);
                    return activity;
                }
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 对象转集合
     */
    public static Map<String, String> beanToMapString(Object object) {
        HashMap<String, String> map = new HashMap<>();
        Class<?> aClass = object.getClass();
        Field[] fields = aClass.getFields();
        for (Field field : fields) {
            field.setAccessible(true);
            try {
                String key = field.getName();
                Object value = field.get(object);
                if (value != null) {
                    map.put(key, value.toString());
                } else {
                    map.put(key, null);
                }
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        return map;
    }

    // 华为
    public static final String PHONE_HUAWEI1 = "Huawei";
    // 华为
    public static final String PHONE_HUAWEI2 = "HUAWEI";
    // 华为
    public static final String PHONE_HUAWEI3 = "HONOR";

    public static boolean isHuaWeiPhone() {
        String brand = Build.BRAND;
        return (!TextUtils.isEmpty(brand) && (PHONE_HUAWEI1.equals(brand) || PHONE_HUAWEI2.equals(brand) || PHONE_HUAWEI3.equals(brand)));
    }

    /**
     * 获取当前应用程序的包名
     *
     * @param context 上下文对象
     * @return 返回包名
     */
    public static String getAppProcessName(Context context) {
        //当前应用pid
        int pid = android.os.Process.myPid();
        //任务管理类
        ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        //遍历所有应用
        List<ActivityManager.RunningAppProcessInfo> infos = manager.getRunningAppProcesses();
        for (ActivityManager.RunningAppProcessInfo info : infos) {
            if (info.pid == pid)//得到当前应用
                return info.processName;//返回包名
        }
        return "";
    }

    /**
     * 方法描述：判断某一应用是否正在运行
     *
     * @param context 上下文
     * @return true 表示正在运行，false 表示没有运行
     */
    public static boolean isAppRunning(Context context) {
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> list = am.getRunningTasks(100);
        if (list.size() <= 0) {
            return false;
        }
        for (ActivityManager.RunningTaskInfo info : list) {
            if (info.baseActivity.getPackageName().equals(getAppProcessName(context))) {
                return true;
            }
        }
        return false;
    }

    /**
     * 检测是否安装支付宝
     *
     * @return * @param context
     */
    public static boolean isInstallAliPay(Context context) {
        Uri uri = Uri.parse("alipays://platformapi/startApp");
        Intent intent = new Intent(Intent.ACTION_VIEW, uri);
        ComponentName componentName = intent.resolveActivity(context.getPackageManager());
        return componentName != null;

    }

    /**
     * 是否安装微信
     *
     * @return true 安装 false 未安装
     */
    public static boolean isInstallWx(Context activity) {
        final PackageManager packageManager = activity.getPackageManager();// 获取packagemanager
        List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);// 获取所有已安装程序的包信息
        if (pinfo != null) {
            for (int i = 0; i < pinfo.size(); i++) {
                String pn = pinfo.get(i).packageName;
                if (pn.equals("com.tencent.mm")) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 判断是否是手机号
     *
     * @param mobile
     * @return
     */
    public static boolean isMobile(String mobile) {
        String regex = "^$|^1[3-9]\\d{9}$";
        Pattern p = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
        Matcher m = p.matcher(mobile);
        return m.matches();
    }

    public static String stringFilter(String str) throws PatternSyntaxException {
// 只允许字母、数字和汉字其余的还可以随时添加比如下划线什么的，但是注意引文符号和中文符号区别
        String regEx = "[^a-zA-Z0-9\u4E00-\u9FA5]";//正则表达式
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(str);
        return m.replaceAll("").trim();
    }

    public static String replaceBlank(String str) {
        String dest = "";
        if (str != null) {
            Pattern p = Pattern.compile("\\s*|\t|\r|\n");
            Matcher m = p.matcher(str);
            dest = m.replaceAll("");
        }
        return dest;
    }

    public static Double foramtMony(Double d) {
        DecimalFormat df = new DecimalFormat("#.00");  //"#.00"  #表示小数点前面任意位数
        String s = df.format(d);  //d不能为字符串
        return Double.parseDouble(s);
    }

    public static Double foramtMony(Long d) {
        DecimalFormat df = new DecimalFormat("#.00");  //"#.00"  #表示小数点前面任意位数
        String s = df.format(d);  //d不能为字符串
        return Double.parseDouble(s);
    }

    @NotNull
    public static Double foramtMony(float d) {
        DecimalFormat df = new DecimalFormat("#.00");  //"#.00"  #表示小数点前面任意位数
        String s = df.format(d);  //d不能为字符串
        return Double.parseDouble(s);
    }

    @NotNull
    public static Float formatNum(float d) {
        DecimalFormat df = new DecimalFormat("#.0");  //"#.00"  #表示小数点前面任意位数
        String s = df.format(d);  //d不能为字符串
        return Float.parseFloat(s);
    }

    /**
     * 取整
     *
     * @author: merbng
     * @time: 2021/10/21 15:04
     * @description:
     */
    public static String foramtMonyNoZero(String num) {
        StringBuilder myNum = new StringBuilder();
        try {
            String integerNum = num.substring(0, num.indexOf("."));
            String decimals = num.substring(num.indexOf("."), num.length());
            float decimalsNum = Float.valueOf(decimals);
            if (decimalsNum > 0) {
                myNum = myNum.append(integerNum).append(decimals);
            } else {
                myNum = myNum.append(integerNum);
            }
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        return String.valueOf(myNum);
    }

    public static String getWeek(long time) {
        try {
            Date week_time = new Date(time);
            System.out.print(week_time);
            SimpleDateFormat s = new SimpleDateFormat("EE");
            String week = s.format(week_time);
            return week;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void contentClipboard(Context context, String content, String toastStr) {
        //获取剪贴板管理器：
        ClipboardManager cm = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
        // 创建普通字符型ClipData
        ClipData mClipData = ClipData.newPlainText("Label", content);
        // 将ClipData内容放到系统剪贴板里。
        cm.setPrimaryClip(mClipData);
        if (!TextUtils.isEmpty(toastStr)) {
            ToastUtils.showShort(context, toastStr);
        } else {
            ToastUtils.showShort(context, "复制成功");
        }
    }

    // 0专栏文章 1专栏评论 2动态 3动态评论 4话题评论 5话题动态评论 6酒窖动态 7酒窖动态评论 8讲坛评论
    public static String getCommentType(int key) {
        HashMap<Integer, String> map = new HashMap<>();
        map.put(0, "专栏文章");
        map.put(1, "专栏评论");
        map.put(2, "动态");
        map.put(3, "动态评论");
        map.put(4, "话题评论");
        map.put(5, "话题动态评论");
        map.put(6, "酒窖动态");
        map.put(7, "酒窖动态评论");
        map.put(8, "讲坛评论");

        if (map.containsKey(key)) {
            return map.get(key);
        } else {
            return "";
        }
    }

    @SuppressLint("NewApi")
    public static boolean isNavigationBarShow_Xiaomi(Context context) {
        //如是是true 的话就是隐藏的虚拟导航栏，反之是显示导航栏
        return !(Settings.Global.getInt(context.getContentResolver(), "force_fsg_nav_bar", 0) != 0);
    }

    public static boolean isNavigationBarShow_HUIWEI(Context context) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
            Display display = windowManager.getDefaultDisplay();
            Point size = new Point();
            Point realSize = new Point();
            display.getSize(size);
            display.getRealSize(realSize);
            boolean result = realSize.y != size.y;
            return realSize.y != size.y;
        } else {
            boolean menu = ViewConfiguration.get(context).hasPermanentMenuKey();
            boolean back = KeyCharacterMap.deviceHasKey(KeyEvent.KEYCODE_BACK);
            if (menu || back) {
                return false;
            } else {
                return true;
            }
        }
    }

    public static String getIPAddress(Context context) {
        NetworkInfo info = ((ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();
        if (info != null && info.isConnected()) {
            if (info.getType() == ConnectivityManager.TYPE_MOBILE) {//当前使用2G/3G/4G网络
                try {
                    //Enumeration<NetworkInterface> en=NetworkInterface.getNetworkInterfaces();
                    for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {
                        NetworkInterface intf = en.nextElement();
                        for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
                            InetAddress inetAddress = enumIpAddr.nextElement();
                            if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address) {
                                return inetAddress.getHostAddress();
                            }
                        }
                    }
                } catch (SocketException e) {
                    e.printStackTrace();
                }

            } else if (info.getType() == ConnectivityManager.TYPE_WIFI) {//当前使用无线网络
                WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
                WifiInfo wifiInfo = wifiManager.getConnectionInfo();
                String ipAddress = intIP2StringIP(wifiInfo.getIpAddress());//得到IPV4地址
                return ipAddress;
            }
        } else {
            //当前无网络连接,请在设置中打开网络
        }
        return null;
    }

    /**
     * 将得到的int类型的IP转换为String类型
     *
     * @param ip
     * @return
     */
    public static String intIP2StringIP(int ip) {
        return (ip & 0xFF) + "." +
                ((ip >> 8) & 0xFF) + "." +
                ((ip >> 16) & 0xFF) + "." +
                (ip >> 24 & 0xFF);
    }


    public static List<String> getListString() {
        String url1 = "https://ss0.bdstatic.com/70cFvHSh_Q1YnxGkpoWK1HF6hhy/it/u=2836123484,3030068744&fm=26&gp=0.jpg";
        String url2 = "https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=1789569952,4029204763&fm=26&gp=0.jpg";
        String url3 = "https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=3580978037,2393601368&fm=26&gp=0.jpg";
        String url4 = "https://ss1.bdstatic.com/70cFuXSh_Q1YnxGkpoWK1HF6hhy/it/u=1556616674,3087626701&fm=26&gp=0.jpg";
        String url5 = "https://ss0.bdstatic.com/70cFvHSh_Q1YnxGkpoWK1HF6hhy/it/u=4001861342,3804929732&fm=26&gp=0.jpg";
        String url6 = "https://ss1.bdstatic.com/70cFuXSh_Q1YnxGkpoWK1HF6hhy/it/u=3600014478,753553017&fm=26&gp=0.jpg";
        String url7 = "https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=2024758634,1516103747&fm=26&gp=0.jpg";
        String url8 = "https://ss0.bdstatic.com/70cFvHSh_Q1YnxGkpoWK1HF6hhy/it/u=2334656353,474671771&fm=26&gp=0.jpg";
        return new ArrayList<String>(Arrays.asList(url1, url2, url3, url4, url5, url6, url7, url8));
    }

    public static String getDateToString(String time) {
        long lcc = 0;
        try {
            lcc = Long.parseLong(time);
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        Date d = new Date(lcc);
        @SuppressLint("SimpleDateFormat")
        SimpleDateFormat sdr = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        return sdr.format(d);
    }

    public static String getLiveTime(String time) {
        long lcc = 0;
        try {
            lcc = Long.parseLong(time);
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        Date d = new Date(lcc);
        @SuppressLint("SimpleDateFormat")
        SimpleDateFormat sdr = new SimpleDateFormat("HH:mm");
        return sdr.format(d);
    }

    public static String getArticleTime(String time) {
        long lcc = 0;
        try {
            lcc = Long.parseLong(time);
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        Date d = new Date(lcc);
        @SuppressLint("SimpleDateFormat")
        SimpleDateFormat sdr = new SimpleDateFormat("MM-dd HH:mm");
        return sdr.format(d);
    }

    public static String getBannerTime(String time) {
        long lcc = 0;
        try {
            lcc = Long.parseLong(time);
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        Date d = new Date(lcc);
        @SuppressLint("SimpleDateFormat")
        SimpleDateFormat sdr = new SimpleDateFormat("yyyy-MM-dd");
        return sdr.format(d);
    }

    private static final String TAG = "CommonUtil";

    public static String getDuration(Context context, String rel_time, String now_time) {
//        Log.i(TAG, "getDuration: rel_time " + rel_time);
//        Log.i(TAG, "getDuration: now_time " + now_time);
        if (TextUtils.isEmpty(now_time)) {
            if (!TextUtils.isEmpty(rel_time)) {
                String showTime = rel_time.substring(0, rel_time.lastIndexOf(":"));

                return showTime;
            }

            return "时间错误";
        }

        String backStr = "";
        @SuppressLint("SimpleDateFormat")
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        Date d1 = null;
        Date d2 = null;

        try {
            d1 = format.parse(rel_time);
            d2 = format.parse(now_time);
            // 毫秒ms
            long diff = d2.getTime() - d1.getTime();

            long diffMinutes = diff / (60 * 1000) % 60;
            long diffHours = diff / (60 * 60 * 1000) % 24;
            long diffDays = diff / (24 * 60 * 60 * 1000);

            if (diffDays != 0) {
                if (diffDays < 30) {
                    if (1 < diffDays && diffDays < 2) {
                        backStr = context.getString(R.string.yesterday);
                    } else if (1 < diffDays && diffDays < 2) {
                        backStr = context.getString(R.string.The_day_before_yesterday);
                    } else {
                        backStr = String.valueOf(diffDays) + context.getString(R.string.Days_ago);
                    }
                } else {
                    DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
                    Date chatTime = null;
                    try {
                        chatTime = df.parse(rel_time);
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                    backStr = df.format(chatTime);
//                    backStr = context.getString(R.string.long_long_ago);
                }
            } else if (diffHours != 0) {
                backStr = String.valueOf(diffHours) + context.getString(R.string.An_hour_ago);

            } else if (diffMinutes != 0) {
                backStr = String.valueOf(diffMinutes) + context.getString(R.string.minutes_ago);

            } else {
                backStr = context.getString(R.string.just);

            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return backStr;

    }

    /**
     * 判断定位服务是否开启
     *
     * @param
     * @return true 表示开启
     */
    public static boolean isLocationEnabled(Context context) {
        int locationMode = 0;
        String locationProviders;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            try {
                locationMode = Settings.Secure.getInt(context.getContentResolver(), Settings.Secure.LOCATION_MODE);
            } catch (Settings.SettingNotFoundException e) {
                e.printStackTrace();
                return false;
            }
            return locationMode != Settings.Secure.LOCATION_MODE_OFF;
        } else {
            locationProviders = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
            return !TextUtils.isEmpty(locationProviders);
        }
    }

    /**
     * 打开Gps设置界面
     */
    public static void openGpsSettings() {
        Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        ContextUtils.getCurApplication().startActivity(intent);
    }

    public static void hideSoftInput(Activity activity) {
        InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
        View view = activity.getCurrentFocus();
        IBinder b = null;
        if (view != null) b = view.getWindowToken();
        imm.hideSoftInputFromWindow(b, InputMethodManager.HIDE_NOT_ALWAYS);
    }

    public static int getStatusBarHeight(Context context) {
        Resources resources = context.getResources();
        int resourcesId = resources.getIdentifier("status_bar_height", "dimen", "android");
        int height = resources.getDimensionPixelSize(resourcesId);
        return height;
    }


    public static boolean isBlank(String s) {
        return (s == null || s.equals("") || s.equals("null"));
    }

    public static boolean isBlank(Object o) {
        return (o == null);
    }

    public static int dip2px(Context context, float dpValue) {
        float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    public static int px2dip(Context context, float pxValue) {
        float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

    public static int getScreenWidth(Context context) {
        WindowManager manager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        Display display = manager.getDefaultDisplay();
        return display.getWidth();
    }

    public static int getScreenHeight(Context context) {
        WindowManager manager = (WindowManager) context
                .getSystemService(Context.WINDOW_SERVICE);
        Display display = manager.getDefaultDisplay();
        return display.getHeight();
    }

    /**
     * 将px值转换为sp值，保证文字大小不变
     *
     * @param pxValue
     * @param （DisplayMetrics类中属性scaledDensity）
     * @return
     */
    public static int px2sp(Context context, float pxValue) {
        final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
        return (int) (pxValue / fontScale + 0.5f);
    }

    public static void formatNum99(TextView tv, int num) {
        if (num > 99) {
            tv.setTextSize(TypedValue.COMPLEX_UNIT_SP, 7);
            tv.setText("99+");
        } else {
            tv.setTextSize(TypedValue.COMPLEX_UNIT_SP, 9);
            tv.setText(num + "");
        }
    }

    public static String formatNum99(int num) {
        if (num > 99) {
            return "99+";
        } else {
            return num + "";
        }
    }

    public static String formatDistance(int distance) {
        if (distance > 1000) {
            return (Math.round(distance / 100f) / 10f) + " km";
        } else {
            return distance + " m";
        }
    }

    public static void callPhone(Activity mAct, String phoneNum) {
        if (TextUtils.isEmpty(phoneNum)) {
            HKToastUtils.showToast("手机号有误");
        } else {
            Intent intent = new Intent(Intent.ACTION_CALL);
            Uri data = Uri.parse("tel:" + phoneNum);
            intent.setData(data);
            mAct.startActivity(intent);
        }
    }

    public static class Formatter {

        public static String formatTime(int ms) {
            int totalSeconds = (ms + 500) / 1000;//四舍五入
            int seconds = totalSeconds % 60;
            int minutes = totalSeconds / 60 % 60;
            int hours = totalSeconds / 60 / 60;
            String timeStr = "";
            if (hours > 9) {
                timeStr += hours + ":";
            } else if (hours > 0) {
                timeStr += "0" + hours + ":";
            }
            if (minutes > 9) {
                timeStr += minutes + ":";
            } else if (minutes > 0) {
                timeStr += "0" + minutes + ":";
            } else {
                timeStr += "00:";
            }
            if (seconds > 9) {
                timeStr += seconds;
            } else if (seconds > 0) {
                timeStr += "0" + seconds;
            } else {
                timeStr += "00";
            }

            return timeStr;
        }


        public String formatDate(long seconds) {
            String finalStr = "";
            long mills = seconds * 1000;
            Calendar calendar = Calendar.getInstance();
            calendar.setTimeInMillis(mills);
            int hour = calendar.get(Calendar.HOUR_OF_DAY);
            finalStr += (hour < 10 ? "0" + hour : hour) + ":";
            int minute = calendar.get(Calendar.MINUTE);
            finalStr += (minute < 10 ? "0" + minute : minute) + ":";
            int second = calendar.get(Calendar.SECOND);
            finalStr += (second < 10 ? "0" + second : second);

            return finalStr;

        }
    }

    /**
     * @param price
     * @return 新版商城 保留两位小数
     */
    public static String handlePrice(String price) {

        DecimalFormat df = new DecimalFormat("#####0.00");

        if (isDoubleOrFloat(price)) {
            String str = df.format(Double.parseDouble(price));
            return str;
        } else {
            return "";
        }
    }

    private static boolean isDoubleOrFloat(String str) {
        Pattern pattern = Pattern.compile("^[-\\+]?[.\\d]*$");
        return pattern.matcher(str).matches();

    }

    /**
     * Return {@code ""} if string equals null.
     *
     * @param s The string.
     * @return {@code ""} if string equals null
     */
    public static String null2Length0(final String s) {
        return s == null ? "" : s;
    }

    public static boolean isNotEmpty(final Object obj) {
        return !isEmpty(obj);
    }

    /**
     * Return whether object is empty.
     *
     * @param obj The object.
     * @return {@code true}: yes<br>{@code false}: no
     */
    public static boolean isEmpty(final Object obj) {
        if (obj == null) {
            return true;
        }
        if (obj.getClass().isArray() && Array.getLength(obj) == 0) {
            return true;
        }
        if (obj instanceof CharSequence && obj.toString().length() == 0) {
            return true;
        }
        if (obj instanceof Collection && ((Collection) obj).isEmpty()) {
            return true;
        }
        if (obj instanceof Map && ((Map) obj).isEmpty()) {
            return true;
        }
        if (obj instanceof SimpleArrayMap && ((SimpleArrayMap) obj).isEmpty()) {
            return true;
        }
        if (obj instanceof SparseArray && ((SparseArray) obj).size() == 0) {
            return true;
        }
        if (obj instanceof SparseBooleanArray && ((SparseBooleanArray) obj).size() == 0) {
            return true;
        }
        if (obj instanceof SparseIntArray && ((SparseIntArray) obj).size() == 0) {
            return true;
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
            if (obj instanceof SparseLongArray && ((SparseLongArray) obj).size() == 0) {
                return true;
            }
        }
        if (obj instanceof LongSparseArray && ((LongSparseArray) obj).size() == 0) {
            return true;
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            if (obj instanceof LongSparseArray
                    && ((LongSparseArray) obj).size() == 0) {
                return true;
            }
        }
        return false;
    }

    /**
     * 验证身份证号是否符合规则
     *
     * @param text 身份证号
     * @return
     */
    public static boolean personIdValidation(String text) {
        String regx = "([1-9][0-9]{14})([0-9]{2}[0-9xX])?";
        return text.matches(regx);
    }

    /**
     * json 转 List<T>
     */
    public static <T> List<T> jsonToList(String json, Class<T> clazz) {
        return GsonUtils.fromJsonArray(json, clazz);
    }

    /**
     * json 转 List<T>
     */
    public static <T> List<T> jsonToList(Object yourObject, Class<T> clazz) {
        List<T> list = JSON.parseArray(JSON.toJSONString(yourObject), clazz);
        return list;
    }

    /*
        json 转 bean
     */
    public static <T> T jsonToBean(String json, Class<T> clazz) {
        return GsonUtils.parseJsonToBean(json, clazz);
    }

    /*
        bean 转 json
     */
    public static String beanToJson(Object bean) {
        return GsonUtils.toJson(bean);
    }

    public static String list2json(List<Object> list) {
        return JSON.toJSONString(list);
    }

    private static final String SEPARATOR = ",";

    public static String list2str(List<String> list) {
        if (list.size() == 0) return "";
        StringBuilder strBuilder = new StringBuilder();
        for (String letter : list) {
            strBuilder.append(letter);
            strBuilder.append(SEPARATOR);
        }
        String strLetter = strBuilder.toString();
        System.out.println(strLetter);
        //OUTPUT: A,B,C,D,
        //Remove last comma
        return strLetter.substring(0, strLetter.length() - SEPARATOR.length());
    }

    public static String list2strJson(List<String> list) {
        if (list.size() == 0) return "";
        StringBuilder strBuilder = new StringBuilder();
        strBuilder.append("[");
        for (String letter : list) {
            strBuilder.append("\"" + letter + "\"");
            strBuilder.append(SEPARATOR);
        }
        strBuilder.deleteCharAt(strBuilder.length() - 1);
        strBuilder.append("]");
        return strBuilder.toString();
    }

    public static List<String> str2List(String str) {
        return Arrays.asList(str.split(","));
    }

    //获取参数值
    public static String getUrl(String url, String params) {
        url += "&";
        String pattern = "(\\?|&){1}#{0,1}" + params + "=[a-zA-Z0-9]*(&{1})";
        Pattern r = Pattern.compile(pattern);
        Matcher matcher = r.matcher(url);
        if (matcher.find()) {
            //            System.out.println(matcher.group(0));
            return matcher.group(0).split("=")[1].replace("&", "");
        } else {
            return null;
        }
    }

    public static Map<String, String> getParameters(String url) {
        Map<String, String> params = new HashMap<String, String>();
        if (url == null || "".equals(url.trim())) {
            return params;
        }
        try {
            url = URLDecoder.decode(url, "UTF-8");
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        }
        String[] split = url.split("[?]");
        if (split.length == 2 && !"".equals(split[1].trim())) {
            String[] parameters = split[1].split("&");
            if (parameters != null && parameters.length != 0) {
                for (int i = 0; i < parameters.length; i++) {
                    if (parameters[i] != null
                            && parameters[i].trim().contains("=")) {
                        String[] split2 = parameters[i].split("=");
                        //split2可能为1，可能为2
                        if (split2.length == 1) {
                            //有这个参数但是是空的
                            params.put(split2[0], "");
                        } else if (split2.length == 2) {
                            if (!"".equals(split2[0].trim())) {
                                params.put(split2[0], split2[1]);
                            }
                        }
                    }
                }
            }
        }
        return params;
    }



    //检查系统是否关闭app应用的通知权限
    public static boolean isNotificationEnabled(Context context) {
        String CHECK_OP_NO_THROW = "checkOpNoThrow";
        String OP_POST_NOTIFICATION = "OP_POST_NOTIFICATION";
        AppOpsManager mAppOps = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE);
        ApplicationInfo appInfo = context.getApplicationInfo();
        String pkg = context.getApplicationContext().getPackageName();
        int uid = appInfo.uid;
        Class appOpsClass = null;
        /* Context.APP_OPS_MANAGER */
        try {
            appOpsClass = Class.forName(AppOpsManager.class.getName());
            Method checkOpNoThrowMethod = appOpsClass.getMethod(CHECK_OP_NO_THROW, Integer.TYPE,
                    Integer.TYPE, String.class);
            Field opPostNotificationValue = appOpsClass.getDeclaredField(OP_POST_NOTIFICATION);
            int value = (Integer) opPostNotificationValue.get(Integer.class);
            return ((Integer) checkOpNoThrowMethod.invoke(mAppOps, value, uid, pkg) ==
                    AppOpsManager.MODE_ALLOWED);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 通知权限申请
     *
     * @param context
     */
    public static void requestNotify(Context context) {
        /**
         * 跳到通知栏设置界面
         * @param context
         */
        Intent localIntent = new Intent();
        ///< 直接跳转到应用通知设置的代码
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            localIntent.setAction(Settings.ACTION_APP_NOTIFICATION_SETTINGS);
            localIntent.putExtra(Settings.EXTRA_APP_PACKAGE, context.getPackageName());
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP &&
                Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
            localIntent.setAction("android.settings.APP_NOTIFICATION_SETTINGS");
            localIntent.putExtra("app_package", context.getPackageName());
            localIntent.putExtra("app_uid", context.getApplicationInfo().uid);
        } else if (Build.VERSION.SDK_INT == Build.VERSION_CODES.KITKAT) {
            localIntent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
            localIntent.addCategory(Intent.CATEGORY_DEFAULT);
            localIntent.setData(Uri.parse("package:" + context.getPackageName()));
        } else {
            ///< 4.4以下没有从app跳转到应用通知设置页面的Action，可考虑跳转到应用详情页面,
            localIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            if (Build.VERSION.SDK_INT >= 9) {
                localIntent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
                localIntent.setData(Uri.fromParts("package", context.getPackageName(), null));
            } else if (Build.VERSION.SDK_INT <= 8) {
                localIntent.setAction(Intent.ACTION_VIEW);
                localIntent.setClassName("com.android.settings", "com.android.setting.InstalledAppDetails");
                localIntent.putExtra("com.android.settings.ApplicationPkgName", context.getPackageName());
            }
        }
        context.startActivity(localIntent);
    }

    public static String getParams(HashMap<String, String> mParams) {
      /*  HashMap<String, String> mParams = new HashMap<>();
        mParams.put("entryId", String.valueOf(entryId));*/
        String url = "";
        if (mParams != null) {
            StringBuilder sb = new StringBuilder();
            sb.append("?");
            for (Map.Entry<String, String> entry : mParams.entrySet()) {
                sb.append(entry.getKey());
                sb.append("=");
                sb.append(entry.getValue());
                sb.append("&");
            }
            url = sb.toString();
        }
        return url.substring(0, url.length() - 1);
    }

    /**
     * 渐变动画
     *
     * @param view 执行该动画的view对象
     */
    public static AlphaAnimation shadeAnim(View view) {
        AlphaAnimation alphaAnimation = new AlphaAnimation(0.1f, 1.0f);
        alphaAnimation.setDuration(1000);
        alphaAnimation.setRepeatCount(-1);
        alphaAnimation.setRepeatMode(Animation.REVERSE);
        alphaAnimation.start();
        view.setAnimation(alphaAnimation);
        return alphaAnimation;
    }

    /**
     * EditText竖直方向是否可以滚动
     * <p>
     * https://www.jb51.net/article/86932.htm
     *
     * @param editText 需要判断的EditText
     * @return true：可以滚动  false：不可以滚动
     */
    public static boolean canVerticalScroll(EditText editText) {
        //滚动的距离
        int scrollY = editText.getScrollY();
        //控件内容的总高度
        int scrollRange = editText.getLayout().getHeight();
        //控件实际显示的高度
        int scrollExtent = editText.getHeight() - editText.getCompoundPaddingTop() - editText.getCompoundPaddingBottom();
        //控件内容总高度与实际显示高度的差值
        int scrollDifference = scrollRange - scrollExtent;

        if (scrollDifference == 0) {
            return false;
        }

        return (scrollY > 0) || (scrollY < scrollDifference - 1);
    }

    /**
     * 检查权限列表
     *
     * @param context
     * @param op       这个值被hide了，去AppOpsManager类源码找，如位置权限  AppOpsManager.OP_GPS==2
     * @param opString 如判断定位权限 AppOpsManager.OPSTR_FINE_LOCATION
     * @return @see 如果返回值 AppOpsManagerCompat.MODE_IGNORED 表示被禁用了
     */
    public static int checkOp(Context context, int op, String opString) {
        final int version = Build.VERSION.SDK_INT;
        if (version >= 19) {
            Object object = context.getSystemService(Context.APP_OPS_SERVICE);
//            Object object = context.getSystemService("appops");
            Class c = object.getClass();
            try {
                Class[] cArg = new Class[3];
                cArg[0] = int.class;
                cArg[1] = int.class;
                cArg[2] = String.class;
                Method lMethod = c.getDeclaredMethod("checkOp", cArg);
                return (Integer) lMethod.invoke(object, op, Binder.getCallingUid(), context.getPackageName());
            } catch (Exception e) {
                e.printStackTrace();
                if (Build.VERSION.SDK_INT >= 23) {
                    return AppOpsManagerCompat.noteOp(context, opString, context.getApplicationInfo().uid,
                            context.getPackageName());
                }

            }
        }
        return -1;
    }

    /**
     * 打开美洽客服
     *
     * @param activity
     */
    public static void openCustomerService(Activity activity) {
        //美洽
        // 相同的 id 会被识别为同一个顾客
        int uid = 0;
        String avatar = "";
        String name = "";
        if (SpUtils.getInstance().getLoadUserBean() != null && SpUtils.getInstance().getLoadUserBean().getData() != null) {
            uid = SpUtils.getInstance().getLoadUserBean().getData().getId();
            avatar = SpUtils.getInstance().getLoadUserBean().getData().getIcon();
            name = SpUtils.getInstance().getLoadUserBean().getData().getName();
        }
        if (uid != 0 && !avatar.equals("")) {
            HashMap<String, String> clientInfo = new HashMap<>();
            clientInfo.put("name", name);
            clientInfo.put("avatar", avatar);
            Intent intent = new MQIntentBuilder(activity).setCustomizedId(String.valueOf(uid)).setClientInfo(clientInfo).build();
            activity.startActivity(intent);
        } else {
            Intent intent = new MQIntentBuilder(activity).build();
            activity.startActivity(intent);
        }
    }

}
